<script setup>
// 提示框
import baseModel from "@/components/baseModel/baseModel.vue";
import { computed, reactive, ref } from "vue";
import request from "@/common/utils/request";
import { message } from 'ant-design-vue';
// 选择素材
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";

// 可编辑头部
import EditableHead from "@/views/shotstack/MuseMixedCut/components/EditableHead.vue";

// 查看视频弹窗
import viewVideo from '../../../../../views/shotstack/components/dialogComponent/viewVideo.vue'
// import viewVideo from '@/views/shotstack/components/dialogComponent/ViewVideo.vue'
const viewVideoRef = ref(null)

// 添加标签弹窗
// import addTags from './addTags.vue'

// 添加标签实例
// const addTagsRef = ref(null)

// const addTag = () => {
//   addTagsRef.value && addTagsRef.value.open()
// }

// 判断本条数据类型 是否是自定义
const customType = computed(() => {
  return state.detail?.type == 'auto_custom'
})

const emit = defineEmits('dialogSubmit:data')

const state = reactive({
  videoUrl: '',
  type: 1,
  id: '',
  spinning: false,
  // 渲染的详情数据
  detail: {},
  // 标签组
  tagsArr: [],
  // 是否展示修改素材
  showMultimediaChange: false,
  // 选择素材库视频
  addVisible: false
});

let formState = reactive({
  text: "",
});

// 视频链接表单
const formLink = reactive({
  text_source: ''
});



const columns = reactive([
  {
    title: "场景描述",
    dataIndex: "scene_des",
    key: "scene_des",
    // align: "center",
  },
  {
    title: "字幕内容",
    dataIndex: "subtitle_content",
    key: "subtitle_content",
    // align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    width: 100,
  },
]);

const toView = () => {
  if (!state.detail?.material_url) return message.error('当前没有可预览的视频!')
  viewVideoRef.value && viewVideoRef.value.open(state.detail.material_url)
}

const dialog = ref(null);

// 校验至少三十个字符
const minLengthValidator = (rule, value, callback) => {
  const trimmedValue = value.replace(/\s+/g, '');
  if (trimmedValue.length < 30) {
    callback(new Error('文案至少需要30个字符（不含空格）'));
  } else {
    callback();
  }
}

const submitFn = async () => {
  // 如果正在加载, 不发送任何请求
  if (state.spinning) {
    dialog.value && dialog.value.closeModal();
    return
  }

  // 手动创建生成的, 无需判断视频链接

  let promiseArr = customType.value
    ? [textFormRef.value.validate()]
    : [linkFormRef.value.validate(), textFormRef.value.validate()]

  // 手动创建生成的ai记录
  Promise.all(promiseArr).then(() => {
    const params = Object.assign({}, formState, formLink, {
      id: state.id,
    })
    request.put('work_ai', `/user/shotstack/inspirationText/update`, params)
    dialog.value && dialog.value.closeModal();
    emit('dialogSubmit')
  }).catch(() => {
    message.error(customType.value ? '请完善文案信息!' : '请完善文案和视频链接信息!')
  })

  // Promise.all([linkFormRef.value.validate(), textFormRef.value.validate()]).then(() => {
  //   const params = Object.assign({}, formState, formLink, {
  //     id: state.id,
  //   })
  //   request.put('work_ai', `/user/shotstack/inspirationText/update`, params)
  //   dialog.value && dialog.value.closeModal();
  //   emit('dialogSubmit')
  // }).catch(() => {
  //   message.error('请完善文案和视频链接信息!')
  // })

}

// 打开弹窗
const openDialog = (id) => {
  state.detail = {}
  formState.text = ''
  formLink.text_source = ''
  dialog.value.showModal();
  state.id = id
  getData()
  getTags()
};

const getData = async () => {
  try {
    state.spinning = true
    const res = await request.get('work_ai', `/user/shotstack/inspirationText/detail?id=${state.id}`)
    console.log(res, '当前灵感的处理情况');
    // 还在处理中 - 轮询请求处理进程
    if (res.result.status_text == '处理中') {
      getProcess()
    } else {
      // 本身就是完成的状态
      state.detail = res.result
      formState.text = res.result.text
      formLink.text_source = res.result.text_source
      state.spinning = false
    }
  } catch (error) {
    state.spinning = false
  }
}

// 轮询请求处理进程
const timeOutId = ref('')
const getProcess = async () => {
  try {
    const res = await request.get('work_ai', `/user/shotstack/inspirationText/process?id=${state.id}`)
    console.log(res, '处理进程----------------');
    if (res.result.process != 'done') {
      timeOutId.value = setTimeout(() => {
        getProcess()
      }, 3000)
    } else if (res.result.process == 'done' && res.result.fail_reason != '') {
      timeOutId.value && clearTimeout(timeOutId.value)
      // 处理结束 但是有问题, 仅做提示不做处理
      getDetail()
      message.warning(res.result.fail_reason)
      state.spinning = false
    } else {
      // 处理结束 没有问题 获取详情
      timeOutId.value && clearTimeout(timeOutId.value)
      getDetail()
    }
  } catch (error) {
    timeOutId.value && clearTimeout(timeOutId.value)
    state.spinning = false
  }
}

// 获取详情
const getDetail = async () => {
  try {
    const res = await request.get('work_ai', `/user/shotstack/inspirationText/detail?id=${state.id}`)
    console.log(res, '灵感详情');
    state.detail = res.result
    formState.text = res.result.text
    formLink.text_source = res.result.text_source

    state.spinning = false
  } catch (error) {
    state.spinning = false
  }
}

// 获取筛选标签
const getTags = async () => {
  const res = await request.get('work_ai', '/user/shotstack/inspirationText/groupTags')
  console.log(res, '标签列表');
  state.tagsArr = res.result
}

const linkFormRef = ref(null)

// 重新提取视频链接
const reextract = async () => {
  try {
    const valid = await linkFormRef.value.validate()
    const params = {
      id: state.id,
      text_source: formLink.text_source
    }
    const res = await request.put('work_ai', `/user/shotstack/inspirationText/update`, params)
    getData()
  } catch (error) {
    message.error('视频链接不能为空')
  }

}

// 文字表单
const textFormRef = ref(null)

// 重新拆分
// const ressetSplit = async () => {
//   try {
//     const valid =  await textFormRef.value.validate()
//   const params = {
//   id: state.id,
//   text:formState.text
// }
// const res = await request.put('work_ai', `/user/shotstack/inspirationText/update`,params)
// getData()
//     } catch (error) {
//     console.log(error, '表单校验失败');
//     message.error('文案不能为空')
//   }
// }

// 删除某个灵感文案
const deletText = async (id) => {
  const res = await request.del('work_ai', `/user/shotstack/inspirationTextSplit/delete?id=${id}&inspiration_text_id=${state.id}`)
  getData()
}

// 修改标签
// const tagChange = async (bindTags) => {
//   const params = {
//     bindTags,
//     inspiration_text_id:state.id
//   }
//     const res = await request.post('work_ai', `/user/shotstack/inspirationText/bindTags`, params)
//   console.log(res,' 修改灵感标签===============');
//   getData()
// }

// 修改素材库素材
const changeMultimedia_id = async () => {
  if (state.detail?.from_type_text != '素材库') return
  state.addVisible = true
}



// 关闭弹窗, 获取选择的文件
const closeChooseMaterial = (data) => {
  // debugger
  data && (async () => {
    // state.detail.multimedia_id = data.id
    const params = {
      id: state.id,
      multimedia_id: data.id,
    }
    const res = await request.put('work_ai', `/user/shotstack/inspirationText/update`, params)
    console.log(res, ' 修改灵感标签===============');
    getData()
  })()
  state.addVisible = false;
  console.log(data, '选择的视频');
};


// 编辑标题
const changeTitle = async (title) => {
  // debugger
  console.log(title, '修改标题');
  const params = {
    id: state.id,
    title,
  }
  const res = await request.put('work_ai', `/user/shotstack/inspirationText/update`, params)
  console.log(res, ' 修改视频标题===============');
  getData()
}

// 弹窗关闭, 停止轮询
const dialogClose = () => {
  timeOutId.value && clearTimeout(timeOutId.value)

}

const closeDialog = () => {
  // 重置表单的校验
  dialog.value.closeModal();
  state.detail = {}
  formState.text = ''
  formLink.text_source = ''
  linkFormRef.value.clearValidate()
  textFormRef.value.clearValidate()
};

defineExpose({
  openDialog,
  closeDialog,
});

</script>

<template>
  <div>
    <!-- :contentWidth="1298"  -->
    <baseModel ref="dialog" :centered="true" :contentWidth="1318" @cancel="closeDialog()" @submit="submitFn"
      @isClose="dialogClose" :destroyOnClose="true">
      <template #title>
        <!-- - {{ state?.detail?.from_type_text }} -->
        <span>提取视频文字</span>
        <!-- {{ state.detail }} -->
      </template>

      <template #content>
        <a-spin size="large" :spinning="state.spinning" tip="下载视频并解析文案中..." style="margin-top: 12%;">
          <div class="extract_videotext">
            <!-- 左侧区域 -->
            <div class="lf">
              <!-- 顶部视频信息 -->
              <div class="top-videoInfo">
                <!-- v-if="state.detail?.from_type_text == '素材库'" -->
                <div class="videoInfo_lf" @mouseenter="state.showMultimediaChange = true"
                  @mouseleave="state.showMultimediaChange = false">
                  <img v-if="state.detail?.cover_url" class="video" :src="state.detail?.cover_url" alt="" />
                  <div v-else
                    style="width: 100%; height: 260px; display: flex; align-items: center; justify-content: center;">
                    <a-empty :description="null" />
                  </div>
                  <!-- 上传素材遮罩 -->
                  <div class="video_upload" v-show="state.showMultimediaChange == true">
                    <!-- <span class="video_title">添加素材:</span> -->
                    <div class="video_con">
                      <div class="operate_con">
                        <!-- 切换 -->
                        <cu-icon @click="changeMultimedia_id" type="icon-qiehuan" class="delete_icon"
                          v-if="state.detail?.from_type_text == '素材库'" />
                        <!-- 预览 -->
                        <cu-icon type="icon-a-bofang1x1" class="delete_icon" @click="toView" />
                        <!-- <span class="replace">替换素材</span> -->
                      </div>
                    </div>
                  </div>
                </div>
                <!-- <div  class="videoInfo_lf">
            <img
           v-if="state.detail?.cover_url"
             class="video"
             :src="state.detail?.cover_url"
             alt=""
           />
           <div v-else style="width: 100%; height: 260px; display: flex; align-items: center; justify-content: center;">
             <a-spin />

           </div>
          </div> -->
                <div class="videoInfo_rg">
                  <div class="video_msg">
                    <!-- <p class="desc" v-if="!state.detail?.title"> {{ '暂无标题' }} </p> -->
                    <EditableHead :placeholder="'请输入标题'" style="width: 100%;" :titleText="state?.detail.title || '暂无标题'"
                      @changeTitle="changeTitle"></EditableHead>
                    <div class="video_msg_items">
                      <!-- 发布时间 -->
                      <div class="video_msg_item">发布时间：{{ state.detail?.publish_time || '----' }}</div>
                      <!-- 持续时间 -->
                      <div class="video_msg_item">视频时长：{{ state.detail?.material_duration_text || '----' }}</div>
                      <!-- 视频来源 -->
                      <div class="video_msg_item">视频来源：{{ state.detail?.from_type_text || '----' }}</div>
                    </div>
                  </div>
                  <!-- 头像 -->
                  <div class="avatar">
                    <img class="video" :src="state.detail?.avatar" alt="" />
                    <div class="user_info">
                      <span class="name">{{ state.detail?.author || '----' }}</span>
                      <span class="followers">粉丝数 {{ state.detail?.fans_text || '----' }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 中间统计区域 -->
              <div class="middle-count">
                <div class="count_item">
                  <span class="count">{{ state.detail?.like_text || '----' }}</span>
                  <span class="count_desc">点赞数</span>
                </div>
                <div class="count_item">
                  <span class="count">{{ state.detail?.comment_text || '----' }}</span>
                  <span class="count_desc">评论数</span>
                </div>
                <div class="count_item">
                  <span class="count">{{ state.detail?.collect_text || '----' }}</span>
                  <span class="count_desc">收藏数</span>
                </div>
                <div class="count_item">
                  <span class="count">{{ state.detail?.share_text || '----' }}</span>
                  <span class="count_desc">互动总数</span>
                </div>
              </div>
              <!-- 视频链接 -->
              <div class="video_link">
                <!-- <div style="color: #7f7f7f; font-weight: 500">视频链接：</div> -->
                <a-form layout="vertical" ref="linkFormRef" :model="formLink" style="margin-top: 10px">
                  <a-form-item label="视频链接：" name="text_source" :rules="[
                    { required: true, trigger: 'change', message: '请粘贴视频链接' },
                  ]">
                    <a-textarea :disabled="state.detail?.from_type_text == '素材库'" placeholder="请粘贴短视频链接，视频时长不超过20分钟"
                      :auto-size="{ minRows: 5, maxRows: 5 }" allowClear class="link_textarea"
                      v-model:value="formLink.text_source"></a-textarea>
                  </a-form-item>
                </a-form>
                <!-- <a-textarea
            :disabled="state.detail?.from_type_text == '素材库'"
            placeholder="请粘贴短视频链接，视频时长不超过20分钟"
            :auto-size="{ minRows: 5, maxRows: 5 }"
            allowClear
            class="link_textarea"
            v-model:value="formLink.text_source"
          ></a-textarea> -->
                <div class="extract">
                  <span class="extract_time" v-show="state.detail?.publish_time">提取时间：{{ state.detail?.publish_time ||
                    '--' }}</span>
                  <a-button :disabled="state.detail?.from_type_text == '素材库'" @click="reextract">重新提取</a-button>
                </div>
                <!-- <div class="label">
            <div>标签</div>
            <a-space>
              <a-tag style="cursor: pointer;" class="tag_select" @click="addTag">+请选择标签</a-tag>
              <a-tag class="tag_select" v-for="i in state.detail?.bind_tags" :key="i.id">{{ i?.tag?.name }}</a-tag>
            </a-space>
          </div> -->
              </div>
            </div>
            <!-- 右侧区域 -->
            <div class="rg">
              <!-- <div style="text-align: right">
          <a-button @click="ressetSplit">重新拆分</a-button>
        </div> -->
              <!-- 文案 -->
              <div class="text_writing">
                <a-form layout="vertical" ref="textFormRef" :model="formState" style="margin-top: 10px">
                  <a-form-item label="文案：" name="text" :rules="[
                    { required: true, trigger: 'change', message: '请输入文案' },
                    { validator: minLengthValidator, trigger: 'change' }
                  ]">
                    <a-textarea show-count v-model:value="formState.text" placeholder="请输入文案"
                      :auto-size="{ minRows: 5, maxRows: 5 }"></a-textarea>
                  </a-form-item>
                </a-form>
              </div>
              <!-- 列表 -->
              <!-- <a-table
        v-if="false"
          bordered
          :dataSource="state.detail?.text_splits"
          :columns="columns"
          class="table"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a @click="deletText(record.id)">删除</a>
            </template>
</template>
</a-table> -->
            </div>
          </div>
        </a-spin>
      </template>
    </baseModel>
  </div>

  <!-- 选择标签 -->
  <!-- <addTags ref="addTagsRef" :list="state.tagsArr" :bind_tags="state.detail.bind_tags"
    @tagChange="tagChange"
    ></addTags> -->

  <!-- 视频预览 -->
  <viewVideo ref="viewVideoRef"></viewVideo>

  <!-- 选择 素材库视频 -->
  <ChooseMaterial :isClip="false" material_type="video" :visible="state.addVisible" @close="closeChooseMaterial" />
</template>


<style lang="less" scoped>
.extract_videotext {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;

  //   左侧区域
  .lf {
    width: 40%;

    // 顶部视频信息
    .top-videoInfo {
      display: flex;
      width: 100%;

      .videoInfo_lf {
        margin-right: 10px;
        position: relative;
        width: 200px;

        .video {
          width: 200px;
          height: 260px;
          object-fit: cover;
        }

        .video_upload {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;

          // 视频容器
          .video_con {
            width: 100%;
            height: 100%;
            background-color: #0000002c;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;

            .operate_con {
              opacity: 0;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 20px;
              transition: all 0.3s;
              font-size: 20px;

              .replace {
                color: #fff;
                font-size: 16px;
                cursor: pointer;

              }

            }

            &:hover {
              .operate_con {
                width: 100%;
                height: 100%;
                position: absolute;
                left: 0;
                top: 0;
                background-color: rgba(0, 0, 0, .3);
                opacity: 1;

                .play_icon {
                  color: #fff;
                  font-size: 24px;
                  cursor: pointer;

                  &:hover {
                    color: #ff5652;
                  }
                }

                .delete_icon {
                  color: #fff;
                  font-size: 34px;
                  cursor: pointer;

                  &:hover {
                    color: #ff5652;
                  }
                }
              }
            }

          }

        }
      }

      .videoInfo_rg {
        flex: 1;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .video_msg {
          .desc {
            font-size: 12px;
            font-weight: 600;
            padding-top: 5px;
            // width: 282px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3;
            overflow: hidden;
            text-overflow: ellipsis;
            /* 适用于IE和一些旧版浏览器 */
          }

          .video_msg_items {
            display: flex;
            flex-direction: column;
            gap: 10px;

            .video_msg_item {
              color: #aaaaaa;
            }
          }
        }

        .avatar {
          display: flex;
          align-items: center;

          img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
          }

          .user_info {
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            font-size: 12px;

            .name {
              font-weight: 600;
              margin-bottom: 2px;
            }

            .followers {
              color: #aaaaaa;
            }
          }
        }
      }
    }

    // 中间统计区域
    .middle-count {
      display: flex;
      justify-content: space-between;
      width: 300px;
      flex-wrap: wrap;
      margin-top: 20px;

      .count_item {
        display: flex;
        justify-content: center;
        width: 50%;
        height: 60px;
        flex-direction: column;

        .count {
          font-weight: 700;
          font-size: 14px;
          color: #7f7f7f;
        }

        .count_desc {
          margin-top: 4px;
          font-weight: 500;
          color: #aaaaaa;
        }
      }
    }

    // 视频链接
    .video_link {
      margin-top: 20px;

      .link_textarea {
        margin-top: 10px;
      }

      .extract {
        align-items: center;
        margin-top: 20px;
        display: flex;
        justify-content: space-between;

        .extract_time {
          color: #aaaaaa;
          font-size: 14px;
        }
      }

      .label {
        margin-top: 20px;

        .tag_select {
          margin-top: 10px;
        }
      }
    }
  }

  //   右侧区域
  .rg {
    flex: 1;

    .text_writing {
      margin-top: 10px;
    }

    .table {
      margin-top: 20px;

      .scene_desc {
        max-width: 200px;
      }

      .subtitle_content {
        max-width: 200px;
      }
    }
  }
}
</style>